<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="primary"
          icon="el-icon-delete"
          class="handle-del mr10"
          @click="delAllSelection"
          >批量禁用</el-button
        >
        <el-button
          type="success"
          icon="el-icon-plus"
          class="handle-del mr10"
          @click="addOne"
          >增加</el-button
        >
        <el-input
          v-model="query.queryParam.userName"
          placeholder="用户名"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"
          >搜索</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="checkSelectable"
        ></el-table-column>
        <el-table-column
          prop="userAccount"
          label="账号"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="姓名"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userSex"
          label="性别"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column label="照片(查看大图)" align="center">
          <template slot-scope="scope">
            <el-image
              class="table-td-thumb"
              :src="scope.row.userPicture"
              :preview-src-list="[scope.row.userPicture]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色" align="center"></el-table-column>
        <el-table-column label="状态" width="68" align="center">
          <template slot-scope="scope">
            <el-tag
              color="Whitesmoke"
              :type="
                scope.row.isDel === 1 ? 'danger' : scope.row.isDel === 0 ? 'success' : ''
              "
              >{{ scope.row.isDel === 0 ? "正常" : "禁用" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="userPhone"
          label="联系方式"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userEmail"
          label="邮箱"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column prop="createTime" label="注册时间"></el-table-column>
        <el-table-column prop="updateTime" label="修改时间"></el-table-column>
        <el-table-column label="操作" width="130" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              >禁用</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :total="total"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form ref="form" :model="form" label-width="70px" :rules="rules">
        <el-form-item label="联系电话" prop="userPhone">
          <el-input type="text" v-model="form.userPhone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input type="text" v-model="form.userEmail"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择">
            <el-option label="无角色" :value=0></el-option>
            <el-option
              v-for="item in roles"
              :key="item.id"
              :value="item.id"
              :label="item.roleName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isDel">
          <el-switch
            v-model="form.isDel"
            active-text="禁用"
            :active-value="1"
            inactive-text="正常"
            :inactive-value="0"
            active-color="#ff4949"
            inactive-color="#13ce66"
          ></el-switch>
        </el-form-item>
        <el-form-item prop="file" label="证件照">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :on-change="checkImage"
            :auto-upload="false"
            accept="image/png,image/jpg,image/jpeg"
          >
            <img v-if="form.userPicture" :src="form.userPicture" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="btnBoolean" @click="saveEdit"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="新增" :visible.sync="addVisible" width="30%">
      <el-form ref="addform" :model="addform" label-width="70px" :rules="rules2">
        <el-form-item label="账号" prop="userAccount">
          <el-input type="text" v-model="addform.userAccount"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="userName">
          <el-input type="text" v-model="addform.userName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="userPhone">
          <el-input type="text" v-model="addform.userPhone"></el-input>
        </el-form-item>
         <el-form-item label="性别" prop="userSex">
          <el-select v-model="addform.userSex">
            <el-option key="man" label="男" value="男"></el-option>
            <el-option key="male" label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input type="text" v-model="addform.userEmail"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="addform.roleId" placeholder="请选择">
            <el-option label="无角色" :value=0></el-option>
            <el-option
              v-for="item in roles"
              :key="item.id"
              :value="item.id"
              :label="item.roleName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="fkClassId">
          <el-select v-model="addform.fkClassId" placeholder="角色为学生请填写此项">
            <el-option label="无班级" :value=0></el-option>
            <el-option
              v-for="item in classes"
              :key="'class-' +item.id"
              :value="item.id"
              :label="item.className"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import validatecommon from "../../utils/validateutils";
var _this;
export default {
  name: "basetable",
  data() {
    return {
      query: {
        queryParam: {
          userName: "",
        },
        pageIndex: 1,
        pageSize: 10,
      },
      tableData: [],
      roles: [],
      classes: [],
      multipleSelection: [],
      delList: [],
      editVisible: false,
      addVisible: false,
      total: 0,
      form: {},
      addform:{},
      rowdata: {},
      file: {},
      btnBoolean: true,
      rules: {
        userPhone: [{ validator: validatecommon.validatePhone, trigger: "blur" }],
        userEmail: [{ validator: validatecommon.validateEmail, trigger: "blur" }],
      },
      rules2: {
        userPhone: [{ validator: validatecommon.validatePhone, trigger: "blur" }],
        userEmail: [{ validator: validatecommon.validateEmail, trigger: "blur" }],
        userAccount:[{ required: true, message: '请输入登录账号', trigger: 'blur' }],
        userName:[{ required: true, message: '请输入姓名', trigger: 'blur' }],
      },
    };
  },
  created() {
    this.getData();
    this.getRoles();
    _this = this;
  },
  methods: {
    // 获取数据
    getData() {
      this.$post("/sys/userlist", this.query).then((res) => {
        if (res.code === 0) {
          this.tableData = res.data.records;
          this.total = res.data.total || 1;
        }
      });
    },
    // 获取角色
    getRoles(){
      this.$post("/role/getnormal", null).then(res => {
        if (res.code === 0) {
          this.roles = res.data;
        }else{
          this.$message.error("角色列表初始化失败！")
        }
      })
    },
    // 是否可选中
    checkSelectable(row) {
      return row.isDel === 0;
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.getData();
    },
    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm("确定要禁用吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          this.delList.push(row.id);
          this.deleteList(this.delList);
        })
        .catch(() => {});
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delAllSelection() {
      this.delList = this.multipleSelection.map((x) => {
        return x.id;
      });
      this.deleteList(this.delList);
      this.multipleSelection = [];
    },
    //删除操作
    deleteList(param) {
      this.$post("/sys/deluser", param).then((res) => {
        if (res.code === 0) {
          this.$message.success("禁用成功");
          this.getData();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 编辑操作
    handleEdit(index, row) {
      this.rowdata = row;
      this.idx = index;
      this.form = JSON.parse(JSON.stringify(row));
      this.editVisible = true;
    },
    addOne(){
      _this.$post('/class/getall', null).then(res=>{
        if (res.code === 0) {
          _this.classes = res.data
        }else{
          _this.$message.error("获取班级列表失败！")
        }
      })
      _this.addVisible = true;
    },
    saveAdd(){
      this.$refs.addform.validate((valid) => {
        if (valid) {
          _this.$post('/sys/saveoneuser', _this.addform).then(res=>{
            if (res.code === 0) {
              this.$message.success(res.msg)
            }else{
              this.$message.error(res.msg)
            }
          })
        }else{
          this.$message.error("输入错误！");
        }
      })
    },
    // 检查图片是否合规
    checkImage(file, fileList) {
      const isJPG =
        file.raw.type === "image/jpeg" ||
        file.raw.type === "image/png" ||
        file.raw.type === "image/jpeg";
      const isLt2M = file.raw.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("请上传类型为png/jpg/jpeg的图片！");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
        return false;
      }

      var img = new Image();
      const isSize = new Promise(function (resolve, reject) {
        const width = 300;
        const height = 500;
        img.onload = function () {
          let valid = img.width / img.height === width / height;
          valid ? resolve() : reject();
        };
        if (window.createObjectURL !== undefined) {
          img.src = window.createObjectURL(file.raw); // basic
        } else if (window.URL !== undefined) {
          img.src = window.URL.createObjectURL(file.raw); // IE,googLe, 360, Safari,firefox
        } else if (window.webkitURL !== undefined) {
          img.src = window.webkitURL.createObjectURL(file.raw); // webkit
        }
      }).then(
        () => {
          this.form.userPicture = img.src;
          this.file = file.raw;
          return file;
        },
        () => {
          _this.$message.error({
            message: "上传图片长宽比为5:3!",
          });

          return Promise.reject();
        }
      );
    },
    // 保存编辑
    saveEdit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("id", this.rowdata.id);
          if (this.rowdata.userPhone !== this.form.userPhone) {
            formData.append("userPhone", this.form.userPhone);
          }
          if (this.rowdata.roleId !== this.form.roleId) {
            formData.append("roleId", this.form.roleId);
          }
          if (this.rowdata.isDel !== this.form.isDel) {
            formData.append("isDel", this.form.isDel);
          }
          if (this.rowdata.userEmail !== this.form.userEmail) {
            formData.append("userEmail", this.form.userEmail);
          }
          if (this.file !== undefined) {
            formData.append("file", this.file);
          }
          this.$post("/sys/updateUser", formData).then((res) => {
            if (res.code === 0) {
              this.$message.success(res.msg);
              this.$emit("closeandreload");
              this.editVisible = false;
              this.form = {};
              this.rowdata = {};
              this.getData();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          this.$message.error("输入错误！");
        }
      });
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.getData();
    },
  },
  watch: {
    form: {
      handler: (val, oldval) => {
        if (JSON.stringify(_this.form) !== JSON.stringify(_this.rowdata)) {
          _this.btnBoolean = false;
        } else {
          _this.btnBoolean = true;
        }
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 150px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
/deep/.el-upload {
  width: 150px;
  height: 210px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 210px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 210px;
  display: block;
}
</style>
